package com.hnyyac.ad.mds.views_notload

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.ViewGroup
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.CSJAdError
import com.bytedance.sdk.openadsdk.CSJSplashAd
import com.bytedance.sdk.openadsdk.TTAdNative.CSJSplashAdListener
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.mediation.MediationConstant
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot
import com.bytedance.sdk.openadsdk.mediation.ad.MediationSplashRequestInfo
import com.bytedance.sdk.openadsdk.mediation.manager.MediationBaseManager
import com.hnyyac.ad.mds.KadControler

class NewGromoreSplashAd(private val activity: Activity, private val listener: IAdviewNotLoadSplashListener) {
    private val TAG = "qin"
    private var mSplashAd: CSJSplashAd? = null
    private lateinit var MyadUnitId: String
    private var hasCalledFillCache = false
    private var timeoutHandler: Handler? = null
    private var timeoutRunnable: Runnable? = null
    private var hasReceivedAnyCallback = false // 标记是否已收到任何回调

    @SuppressLint("SuspiciousIndentation")
    fun load(adUnitId: String, container: ViewGroup, time: Long, isHot: Boolean) {
        MyadUnitId = adUnitId
        hasCalledFillCache = false
        hasReceivedAnyCallback = false // 重置回调标记

        // 清理之前的超时任务
        cleanupTimeout()

        // 创建新的超时任务
        timeoutHandler = Handler(Looper.getMainLooper())
        timeoutRunnable = Runnable {
            if (!hasReceivedAnyCallback) {
                Log.e(TAG, "开屏广告加载总超时（8秒），未收到任何回调")
                listener.onError("开屏广告加载超时")
                //callFillCacheIfNeeded(isHot)

                // 确保清理资源
                onDestroy()
            }
        }

        // 启动8秒超时计时器
        timeoutHandler?.postDelayed(timeoutRunnable!!, 8000)

        // 第一步、创建开屏自定义兜底对象
        // val csjSplashRequestInfo: MediationSplashRequestInfo = object : MediationSplashRequestInfo(
        //     MediationConstant.ADN_PANGLE,  // 穿山甲
        //     "103395885",  // adn开屏广告代码位Id，注意不是聚合广告位Id
        //     "5669830",  // adn应用id，注意要跟初始化传入的保持一致
        //     "" // adn没有appKey时，传入空即可
        // ) {}

        // step1
        val adNativeLoader = TTAdSdk.getAdManager().createAdNative(activity)
        // step2
        val adSlot = AdSlot.Builder()
            .setCodeId(adUnitId)
            .setImageAcceptedSize(1080, 1920) // 单位px
            // .setMediationAdSlot(  // 测试广告位兜底对象
            //     MediationAdSlot.Builder()
            //         // 将自定义兜底对象设置给 AdSlot
            //         .setMediationSplashRequestInfo(csjSplashRequestInfo)
            //         .build()
            // )
            .build()

        adNativeLoader.loadSplashAd(adSlot, object : CSJSplashAdListener {
            override fun onSplashRenderSuccess(csjSplashAd: CSJSplashAd) {
                markCallbackReceived() // 标记已收到回调
                Log.e(TAG, "开屏渲染成功")
                /** 渲染成功后，展示广告  */
                mSplashAd = csjSplashAd
                if (container != null && !activity.isFinishing && !activity.isDestroyed) {
                    // 1. 清除容器内可能存在的旧视图（如加载图）
                    container.removeAllViews()
                    // 2. 安全地展示广告
                    showSplashAd(csjSplashAd, container)
                } else {
                    // 开发者处理跳转到APP主页面逻辑
                    listener.onError("开屏渲染失败")
                   // callFillCacheIfNeeded(isHot)
                }
            }

            override fun onSplashLoadSuccess(p0: CSJSplashAd?) {
                markCallbackReceived() // 标记已收到回调
                p0?.let { listener?.onSuccess(it, adUnitId) }
                mSplashAd = p0
//                if (!isHot) {
//                    KadControler.fristFillCache()
//                }
            }

            override fun onSplashLoadFail(csjAdError: CSJAdError) {
                markCallbackReceived() // 标记已收到回调
                /**仅CSJ
                 * csjAdError.getCode() == 1，物料加载失败
                 *
                 * csjAdError.getCode() == 2，素材加载失败
                 *
                 * csjAdError.getCode() == 3，渲染失败、渲染超时
                 *
                 * csjAdError.getCode() == 23，加载超时
                 *
                 */
                listener?.onError(csjAdError.msg)
                //callFillCacheIfNeeded(isHot)
            }

            override fun onSplashRenderFail(csjSplashAd: CSJSplashAd, csjAdError: CSJAdError) {
                markCallbackReceived() // 标记已收到回调
                Log.e(TAG, "开屏渲染失败" + csjAdError.msg)
                listener.onError("开屏渲染失败" + csjAdError.msg)
               // callFillCacheIfNeeded(isHot)
            }
        }, time.toInt())
    }

    private fun markCallbackReceived() {
        hasReceivedAnyCallback = true
        // 取消超时任务，因为已经收到了回调
        cleanupTimeout()
    }

    private fun cleanupTimeout() {
        timeoutRunnable?.let { runnable ->
            timeoutHandler?.removeCallbacks(runnable)
        }
        timeoutRunnable = null
    }

    private fun showSplashAd(csjSplashAd: CSJSplashAd, mSplashContainer: ViewGroup) {
        csjSplashAd.setSplashAdListener(object : CSJSplashAd.SplashAdListener {
            override fun onSplashAdShow(csjSplashAd: CSJSplashAd) {
                mSplashAd = csjSplashAd
                listener?.onAdShow(csjSplashAd, adUnitId = MyadUnitId, 0)
            }

            override fun onSplashAdClick(csjSplashAd: CSJSplashAd) {
                listener?.onAdClick(csjSplashAd, adUnitId = MyadUnitId)
            }

            override fun onSplashAdClose(csjSplashAd: CSJSplashAd, i: Int) {
                // 广告关闭后，销毁广告页面
                listener?.onAdClose(csjSplashAd, adUnitId = MyadUnitId)
                // 清理超时任务
                cleanupTimeout()
            }
        })
        val splashView = csjSplashAd.splashView

        mSplashContainer.removeAllViews()
        mSplashContainer.addView(splashView)
    }

//    private fun callFillCacheIfNeeded(isHot: Boolean) {
//        if (!isHot && !hasCalledFillCache) {
//            KadControler.fristFillCache()
//            hasCalledFillCache = true // 设置标志为已调用
//        }
//    }

    /**
     * 已经展示过且不再使用的广告需要在合适的时机调用destroy方法及时对广告进行销毁，避免内存异常场景。
     */
    fun onDestroy() {
        // 清理超时任务
        cleanupTimeout()

        if (mSplashAd != null && mSplashAd?.getMediationManager() != null) {
            mSplashAd?.getMediationManager()?.destroy()
        }

        // 清理handler引用
        timeoutHandler = null
    }
}